package com.project.class4_7;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    /**创建lock锁对象*/
    private Lock lockObj = new ReentrantLock();
    private volatile int x = 9;
    public void foo(){

        try {
            //尝试获得锁，如果该锁被其他线程拿起，则返回false
            if(lockObj.tryLock()) {
                for (int i = 0; i < 10; i++) {
                    //Thread.currentThread()表示得到当前线程
                    System.out.println(Thread.currentThread() + "   " + i);

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            else{
                System.out.println("获得锁失败");
            }
        }finally{
            if(lockObj.tryLock()) {
                //释放锁
                lockObj.unlock();
            }
        }
    }
}
